﻿window.$jscript.fn.wxApp = (function () {
    var __FN = function () {
        return new __FN.fn._init();
    };
    var hxt = window.$jscript.fn;
    __FN.fn = __FN.prototype = {
        _init: function () { return this; },
        param: { optor: '', components: {}, link:'' },
        ready: function (options) {
            var self = this;
            $.each(options, function (idx, item) {
                if (self.param.hasOwnProperty(idx)) {
                    self.param[idx] = item;
                }
            });

            window.addEventListener('pageshow', function (e) {
                var a = e || window.event;
                if (a.persisted) {
                    window.location.reload()
                }
            });

            var optor = JSON.parse(hxt.fromBase64(self.param.optor)) || {};
            self.setStore(optor);
            hxt.ready({ link: options.link, reqType: 1, key: optor.openId });
            self.initPage();
        },
        setStore: function (optor) {
            var self = this;
            console.log(optor,'optor')
            optor = optor || {};
            if (!hxt.isArray(optor.uiAccessList)) optor.uiAccessList = [];
            optor.canDo = function (access) {
                var _optor = optor, cando = false;
                access = $.trim('' + access);
                //console.log(_optor.uiAccessList, 'uiAccessList')
                if (access.indexOf('|') >= 0) {
                    $.each(access.split('|'), function (idx, item) {
                        var funcId = $.trim(item);
                        if (funcId.length > 0) {
                            cando = !!_optor.uiAccessList.find(function (im) { return '' + im.flId == funcId; });
                            if (cando) return false;
                        }
                    });
                }
                else if (access.indexOf('&') >= 0) {
                    $.each(access.split('&'), function (idx, item) {
                        var funcId = $.trim(item);
                        if (funcId.length > 0) {
                            cando = !!_optor.uiAccessList.find(function (im) { return '' + im.flId == funcId; });
                            if (!cando) return false;
                        }
                    });
                }
                else {
                    cando = !!_optor.uiAccessList.find(function (im) { return '' + im.flId == access; });
                }
                return cando;
            };
            optor.encode = function (str, isToken) {
                var _optor = optor, data = { error: null, value: '' };
                try {
                    if (!!isToken) {
                        var key = hxt.guid(false).substr(0, 8),
                            a = hxt.md5(key),
                            b = a.substr(0, 16),
                            c = a.split('').reverse().join('').substr(0, 16),
                            o = { exp: new Date().getTime() + 10 * 60 * 1000, data: str },
                            msg = JSON.stringify(o);
                        data.value = key + hxt.aesEncrypt(msg, b, c);
                    }
                    else {
                        var key = ('' + _optor.key).padStart(32, '0');
                        data.value = hxt.aesEncrypt(str, key.substr(0, 16), key.split('').reverse().join('').substr(0, 16));
                    }
                }
                catch (e) {
                    data.error = e.message;
                }
                return data;
            };
            optor.decode = function (str, isToken) {
                var _optor = optor, data = { error: null, value: '' };
                try {
                    if (!!isToken) {
                        str = '' + str;
                        if (str.length <= 8) {
                            data.error = '缺少必须的参数';
                            return data;
                        }
                        var key = str.substr(0, 8),
                            raw = str.substr(8, str.length - 8),
                            a = hxt.md5(key),
                            b = a.substr(0, 16),
                            c = a.split('').reverse().join('').substr(0, 16);
                        data.value = hxt.aesDecrypt(raw, b, c);
                    }
                    else {
                        var key = ('' + _optor.key).padStart(32, '0');
                        data.value = hxt.aesDecrypt(str, key.substr(0, 16), key.split('').reverse().join('').substr(0, 16));
                    }
                }
                catch (e) {
                    data.error = e.message;
                }
                return data;
            };
            optor.download = function (url, name, size) {
                var _optor = optor, str = { url: !!url ? url : '', name: !!name ? name : '', size: size }, browser = hxt.wxBrowser();

                if (!str.url.toLowerCase().startsWith('http://') && !str.url.toLowerCase().startsWith('https://')) return hxt.error('下载地址无效');
                if (!str.name) {
                    var arr = str.url.split('/');
                    str.name = arr[arr.length - 1];
                };
                if (browser == 4) {
                    //小程序
                    var obj = _optor.encode(str, true).value;
                    wx.miniProgram.navigateTo({
                        url: '/pages/index/download?obj=' + obj,
                        success: function (res) {

                        },
                        fail: function (res) {
                            hxt.alert(res.errMsg, '打开下载页面失败');
                        }
                    });
                }
                else if (browser == 1) {
                    //微信内不支持下载，要处理下，引导在浏览器打开
                    if (!!hxt.element.elVue) {
                        str['exp'] = Date.parse(new Date()) / 1000 + 30 * 60;
                        var obj = _optor.encode(str, true).value;
                        var href = hxt.config.link + 'wx/wxDownload?obj=' + obj;
                        hxt.element.elVue.download(href);
                    }
                    else {
                        window.location.href = str.url;
                    }
                }
                else {
                    hxt.downloadFile(str.url, str.name);
                }
            };
            hxt.store = Vue.observable({
                optor: optor
            });
            //console.log(optor)
        },
        initPage: function () {
            var self = this, optor = hxt.store.optor;
            Vue.use(vant.Lazyload);

            Vue.config.ignoredElements = ['wx-open-launch-weapp'];

            Vue.component('hxt-popup', hxt.hxtPopup());
            Vue.component('page-tip', hxt.pageTip());
            Vue.component('hxt-layout', hxt.hxtLayout());
            Vue.component('hxt-refresh', hxt.hxtRefresh());
            Vue.component('hxt-select', hxt.hxtSelect());
            Vue.component('hxt-datetime-picker', hxt.hxtDatetimePicker());
            Vue.component('hxt-dropbutton', hxt.hxtDropbutton());
            Vue.component('hxt-calendar', hxt.hxtCalendar());
            //var routes = [
            //    {
            //        path: '/',
            //        component: function () { return hxt.staticComponent(self.param.components.wxPage, true); },
            //        children: [

            //        ]
            //    },
            //    { path: '*', redirect: "/" }
            //];
            //var router = new VueRouter({
            //    routes: routes
            //});
            hxt.element.elVue = new Vue({
                //router: router,
                data: function () {
                    var _this = this;
                    return {
                        optor: optor,
                        showUserList: false,
                        showHome: false, //是否显示首页悬浮按钮                       
                        initTop: 0.6,
                        loaded: false,
                        showHeader: false,
                        showFoot: false,
                        leftBtn: false,
                        rightBtn: '',

                        sdkAdd: false, //是否初始化微信jsSDK
                        sdkError: null, //jsSDK错误信息

                        downloadShow: false,
                        downloadHref: null
                    };
                },
                watch: {
                    loaded: function (val) {
                        //console.log(val);
                    },
                    sdkAdd: function (val) {
                        if (!!val) {
                            this.jsSDK();
                        }
                    }
                },
                computed: {

                },
                mounted: function () {
                    $('#divLoading').remove();
                },
                methods: {
                    goHome: function () {
                        var _this = this;
                        //if (!!_this.optor.bindList && _this.optor.bindList.length > 1) _this.showUserList = true;
                        //else {
                        hxt.mask();
                        window.location.replace(hxt.config.link + 'wx/go?state=userinfo&userid=' + _this.optor.wx_openId);
                        //}
                    },
                    leftBtnClick: function () {
                        var _this = this;
                        hxt.mask();
                        window.location.replace(hxt.config.link + 'wx/go?state=userinfo&userid=' + _this.optor.wx_openId);
                    },
                    rightBtnClick: function () {
                        var wxPage = this.$refs['wxPage'];
                        if (!!wxPage && !!wxPage && hxt.isFunction(wxPage.rightBtnClick)) wxPage.rightBtnClick();
                    },
                    jsSDK: function () {
                        var _this = this;
                        _this.sdkError = null;
                        var sdk = function (data) {
                            wx.config({
                                debug: false,
                                appId: data.appId,
                                timestamp: data.timestamp,
                                nonceStr: data.nonceStr,
                                signature: data.signature,
                                jsApiList: ['downloadVoice', 'onVoicePlayEnd', 'uploadVoice', 'onVoiceRecordEnd', 'startRecord', 'stopRecord', 'playVoice', 'pauseVoice', 'stopVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getLocalImgData', 'hideAllNonBaseMenuItem', 'chooseWXPay'],
                                openTagList: ['wx-open-launch-weapp']
                            });
                            wx.ready(function () {
                                wx.checkJsApi({
                                    jsApiList: ['downloadVoice', 'onVoicePlayEnd', 'uploadVoice', 'onVoiceRecordEnd', 'startRecord', 'stopRecord', 'playVoice', 'pauseVoice', 'stopVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getLocalImgData', 'hideAllNonBaseMenuItem', 'chooseWXPay'],
                                    fail: function (res) {
                                        _this.sdkError = res.errMsg;
                                    },
                                    success: function (res) {

                                    }
                                });
                                wx.checkJsApi({
                                    jsApiList: ['chooseImage'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
                                    success: function (res) {
                                        console.log(111,res)
                                    }
                                });
                            });
                            wx.error(function (res) {
                                _this.sdkError = res.errMsg;
                            });
                        };
                        hxt.post({
                            showMask: false,
                            showErr: false,
                            error: function (errmsg) {
                                _this.sdkError = errmsg;
                            },
                            url: hxt.config.link + 'wx/jsSDK',
                            data: { url: window.location.href },
                            ok: function (res) {
                                if (res.code != 0) {
                                    _this.sdkError = res.errmsg;
                                    return;
                                }
                                console.log(res)
                                sdk(res.data);
                            }
                        })
                    },
                    download: function (href) {
                        this.downloadHref = href;
                        this.downloadShow = true;
                    },
                    out: function () {
                        var _this = this;
                        hxt.confirm("确定退出登录吗？", function () {
                            hxt.post({
                                url: hxt.config.link + 'wx/wxLogin',
                                data: { openId: _this.optor.openId },
                                ok: function (res) {
                                    if (res.code != 0) return hxt.error('退出登录失败：' + res.errmsg);
                                    var url = 'login?userid=' + _this.optor.wx_openId;
                                    window.open(url);
                                }
                            });
                        });
                    }
                },
                components: {
                    wxPage: function () { return hxt.staticComponent(self.param.components.wxPage, true); },
                    floatButton: hxt.floatButton()
                }
            }).$mount('#wxApp');
        }
    };
    __FN.fn._init.prototype = __FN.fn;
    return __FN.fn;
})();